﻿<script lang="ts" setup name="syssalesreturnorder">
import { ref, reactive, onMounted } from "vue";
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from "element-plus";
import { downloadStreamFile } from "/@/utils/download";
import { useSyssalesreturnorderApi } from '/@/api/order/syssalesreturnorder';
import { useSysOrgApi } from '/@/api/system/sysOrg';
import { useSysUserApi } from '/@/api/system/sysUser';
import { useSyscustomerApi } from '/@/api/interacting/syscustomer';
import { useSyssalesorderApi } from '/@/api/order/syssalesorder';
import editDialog from '/@/views/order/syssalesreturnorder/editDialog.vue'
import detailDialog from '/@/views/order/syssalesreturnorder/component/detailDialog.vue'
import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import ImportData from "/@/components/table/importData.vue";

const syssalesreturnorderApi = useSyssalesreturnorderApi();
const sysOrgApi = useSysOrgApi();
const sysUserApi = useSysUserApi();
const syscustomerApi = useSyscustomerApi();
const syssalesorderApi = useSyssalesorderApi();
const printDialogRef = ref();
const editDialogRef = ref();
const detailDialogRef = ref();
const importDataRef = ref();
const state = reactive({
  exportLoading: false,
  tableLoading: false,
  stores: {},
  showAdvanceQueryUI: false,
  dropdownData: {} as any,
  selectData: [] as any[],
  tableQueryParams: {} as any,
  tableParams: {
    page: 1,
    pageSize: 20,
    total: 0,
    field: 'createTime', // 默认的排序字段
    order: 'descending', // 排序方向
    descStr: 'descending', // 降序排序的关键字符
  },
  tableData: [],
  // 联查数据
  orgList: [] as any[],
  userList: [] as any[],
  customerList: [] as any[],
  salesOrderList: [] as any[],
});

// 页面加载时
onMounted(async () => {
	// 加载机构列表
	try {
		const orgRes = await sysOrgApi.getList();
		state.orgList = orgRes.data.result || [];
	} catch (error) {
		console.error('加载机构列表失败:', error);
	}
	
	// 加载用户列表
	try {
		const userRes = await sysUserApi.getList();
		state.userList = userRes.data.result || [];
	} catch (error) {
		console.error('加载用户列表失败:', error);
	}
	
	// 加载客户列表
	try {
		const customerRes = await syscustomerApi.page({ page: 1, pageSize: 9999 });
		state.customerList = customerRes.data.result?.items || [];
	} catch (error) {
		console.error('加载客户列表失败:', error);
	}
	
	// 加载销售订单列表
	try {
		const salesOrderRes = await syssalesorderApi.page({ page: 1, pageSize: 9999 });
		state.salesOrderList = salesOrderRes.data.result?.items || [];
	} catch (error) {
		console.error('加载销售订单列表失败:', error);
	}
	
	// 加载表格数据
	handleQuery();
});

// 根据ID获取机构名称
const getOrgName = (orgId: number) => {
	const org = state.orgList.find(item => item.id === orgId);
	return org ? org.name : orgId;
};

// 根据ID获取用户名称
const getUserName = (userId: number) => {
	const user = state.userList.find(item => item.id === userId);
	return user ? user.realName : userId;
};

// 根据状态值获取中文描述
const getStatusText = (status: any) => {
	const statusMap: { [key: string]: string } = {
		'1': '草稿',
		'2': '待审核', 
		'3': '驳回',
		'4': '未入库',  // 销售退货订单状态4应该是未入库
		'5': '部分入库', // 销售退货订单状态5应该是部分入库
		'6': '已完成',
		'7': '已关闭',
		'Draft': '草稿',
		'PendingReview': '待审核',
		'Rejected': '驳回',
		'NotOutOfWarehouse': '未入库',  // 销售退货的NotOutOfWarehouse应该是未入库
		'PartiallyOutOfWarehouse': '部分入库', // 销售退货的部分状态应该是部分入库
		'Completed': '已完成',
		'Closed': '已关闭',
		'草稿': '草稿',
		'待审核': '待审核',
		'驳回': '驳回',
		'未入库': '未入库',
		'部分入库': '部分入库',
		'已完成': '已完成',
		'已关闭': '已关闭'
	};
	return statusMap[status] || status;
};

// 根据状态值获取标签类型
const getStatusType = (status: any) => {
	const statusTypeMap: { [key: string]: string } = {
		// 数字状态码
		'1': 'info',           // 草稿 - 蓝色
		'2': 'warning',        // 待审核 - 橙色
		'3': 'danger',         // 驳回 - 红色
		'4': 'warning',        // 未入库 - 橙色
		'5': 'warning',        // 部分入库 - 橙色
		'6': 'success',        // 已完成 - 绿色
		'7': 'info',           // 已关闭 - 蓝色
		// 枚举状态码
		'Draft': 'info',       // 草稿 - 蓝色
		'PendingReview': 'warning',  // 待审核 - 橙色
		'Rejected': 'danger',        // 驳回 - 红色
		'NotOutOfWarehouse': 'warning',     // 未入库 - 橙色
		'PartiallyOutOfWarehouse': 'warning', // 部分入库 - 橙色
		'Completed': 'success',              // 已完成 - 绿色
		'Closed': 'info',                    // 已关闭 - 蓝色
		// 中文状态值（销售退货订单使用）
		'草稿': 'info',           // 草稿 - 蓝色
		'待审核': 'warning',      // 待审核 - 橙色
		'驳回': 'danger',         // 驳回 - 红色
		'未入库': 'warning',      // 未入库 - 橙色
		'部分入库': 'warning',    // 部分入库 - 橙色
		'已完成': 'success',      // 已完成 - 绿色
		'已关闭': 'info',         // 已关闭 - 蓝色
	};
	return statusTypeMap[status] || 'info';
};

// 根据销售单号获取销售退货数量（销售数量）
const getSalesReturnQuantity = (row: any) => {
	if (row.salesOrderNumber) {
		const salesOrder = state.salesOrderList.find(order => order.code === row.salesOrderNumber);
		return salesOrder ? salesOrder.salesQuantity : '--';
	}
	return '--';
};

// 查询操作
const handleQuery = async (params: any = {}) => {
  state.tableLoading = true;
  state.tableParams = Object.assign(state.tableParams, params);
  const result = await syssalesreturnorderApi.page(Object.assign(state.tableQueryParams, state.tableParams)).then(res => res.data.result);
  state.tableParams.total = result?.total;
  state.tableData = result?.items ?? [];
  state.tableLoading = false;
};

// 列排序
const sortChange = async (column: any) => {
  state.tableParams.field = column.prop;
  state.tableParams.order = column.order;
  await handleQuery();
};

// 删除
const delSyssalesreturnorder = (row: any) => {
  ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await syssalesreturnorderApi.delete({ id: row.id });
    handleQuery();
    ElMessage.success("删除成功");
  }).catch(() => {});
};

// 发起审核
const initiateAudit = (row: any) => {
  ElMessageBox.confirm(`确定要发起审核吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      // 更新订单状态为待审核，包含所有必要字段
      await syssalesreturnorderApi.update({
        id: row.id,
        code: row.code,
        documentStatus: 2, // 待审核状态
        returnDate: row.returnDate,
        salesOrderNumber: row.salesOrderNumber,
        customerName: row.customerName,
        contactPerson: row.contactPerson,
        contactMethod: row.contactMethod,
        salesDeptId: row.salesDeptId,
        salesManagerId: row.salesManagerId,
        salesReturnQuantity: row.salesReturnQuantity,
        salesReturnAmount: row.salesReturnAmount,
        goodsName: row.goodsName,
        remark: row.remark,
        updateUserId: 1300000000001,
        updateUserName: "任杰"
      });
      ElMessage.success("发起审核成功");
      handleQuery();
    } catch (error) {
      console.error('发起审核失败:', error);
      ElMessage.error("发起审核失败");
    }
  }).catch(() => {});
};


// 批量删除
const batchDelSyssalesreturnorder = () => {
  ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await syssalesreturnorderApi.batchDelete(state.selectData.map(u => ({ id: u.id }) )).then(res => {
      ElMessage.success(`成功批量删除${res.data.result}条记录`);
      handleQuery();
    });
  }).catch(() => {});
};

// 导出数据
const exportSyssalesreturnorderCommand = async (command: string) => {
  try {
    state.exportLoading = true;
    if (command === 'select') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map(u => u.id) });
      await syssalesreturnorderApi.exportData(params).then(res => downloadStreamFile(res));
    } else if (command === 'current') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams);
      await syssalesreturnorderApi.exportData(params).then(res => downloadStreamFile(res));
    } else if (command === 'all') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
      await syssalesreturnorderApi.exportData(params).then(res => downloadStreamFile(res));
    }
  } finally {
    state.exportLoading = false;
  }
}

handleQuery();
</script>
<template>
  <div class="syssalesreturnorder-container" v-loading="state.exportLoading">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }"> 
      <el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="关键字">
              <el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="退货单号">
              <el-input v-model="state.tableQueryParams.code" clearable placeholder="请输入退货单号"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="单据状态">
              <el-select v-model="state.tableQueryParams.documentStatus" clearable filterable placeholder="请选择单据状态">
                <el-option value="1" label="草稿" />
                <el-option value="2" label="待审核" />
                <el-option value="3" label="驳回" />
                <el-option value="4" label="未入库" />
                <el-option value="6" label="已完成" />
                <el-option value="7" label="已关闭" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="退货日期">
              <el-date-picker type="daterange" v-model="state.tableQueryParams.returnDateRange"  value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="销售单号">
              <el-select v-model="state.tableQueryParams.salesOrderNumber" clearable filterable placeholder="请选择销售单号">
                <el-option
                  v-for="order in state.salesOrderList"
                  :key="order.id"
                  :label="order.code"
                  :value="order.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="客户名称">
              <el-select v-model="state.tableQueryParams.customerName" clearable filterable placeholder="请选择客户名称">
                <el-option
                  v-for="customer in state.customerList"
                  :key="customer.id"
                  :label="customer.customerName"
                  :value="customer.customerName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="联系人">
              <el-input v-model="state.tableQueryParams.contactPerson" clearable placeholder="请输入联系人"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="联系方式">
              <el-input v-model="state.tableQueryParams.contactMethod" clearable placeholder="请输入联系方式"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="销售部门">
              <el-select v-model="state.tableQueryParams.salesDeptId" clearable filterable placeholder="请选择销售部门">
                <el-option
                  v-for="org in state.orgList"
                  :key="org.id"
                  :label="org.name"
                  :value="org.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="销售负责人">
              <el-select v-model="state.tableQueryParams.salesManagerId" clearable filterable placeholder="请选择销售负责人">
                <el-option
                  v-for="user in state.userList"
                  :key="user.id"
                  :label="user.realName"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="退货原因">
              <el-input v-model="state.tableQueryParams.returnReason" clearable placeholder="请输入退货原因"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="备注">
              <el-input v-model="state.tableQueryParams.remark" clearable placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="软删除时间">
              <el-date-picker type="daterange" v-model="state.tableQueryParams.deleteTimeRange"  value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item >
              <el-button-group style="display: flex; align-items: center;">
                <el-button type="primary"  icon="ele-Search" @click="handleQuery" v-auth="'syssalesreturnorder:page'" v-reclick="1000"> 查询 </el-button>
                <el-button icon="ele-Refresh" @click="() => state.tableQueryParams = {}"> 重置 </el-button>
                <el-button icon="ele-ZoomIn" @click="() => state.showAdvanceQueryUI = true" v-if="!state.showAdvanceQueryUI" style="margin-left:5px;"> 高级查询 </el-button>
                <el-button icon="ele-ZoomOut" @click="() => state.showAdvanceQueryUI = false" v-if="state.showAdvanceQueryUI" style="margin-left:5px;"> 隐藏 </el-button>
                <el-button type="danger" style="margin-left:5px;" icon="ele-Delete" @click="batchDelSyssalesreturnorder" :disabled="state.selectData.length == 0" v-auth="'syssalesreturnorder:batchDelete'"> 删除 </el-button>
                <el-button type="primary" style="margin-left:5px;" icon="ele-Plus" @click="editDialogRef.openDialog(null, '新增销售退货')" v-auth="'syssalesreturnorder:add'"> 新增 </el-button>
                <el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportSyssalesreturnorderCommand">
                  <el-button type="primary" style="margin-left:5px;" icon="ele-FolderOpened" v-reclick="20000" v-auth="'syssalesreturnorder:export'"> 导出 </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="select" :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
                      <el-dropdown-item command="current">导出本页</el-dropdown-item>
                      <el-dropdown-item command="all">导出全部</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button type="warning" style="margin-left:5px;" icon="ele-MostlyCloudy" @click="importDataRef.openDialog()" v-auth="'syssalesreturnorder:import'"> 导入 </el-button>
              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="state.tableData" @selection-change="(val: any[]) => { state.selectData = val; }" style="width: 100%" v-loading="state.tableLoading" tooltip-effect="light" row-key="id" @sort-change="sortChange" border>
        <el-table-column type="selection" width="40" align="center" v-if="auth('syssalesreturnorder:batchDelete') || auth('syssalesreturnorder:export')" />
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column prop='code' label='退货单号' show-overflow-tooltip>
          <template #default="scope">
            <el-button type="primary" link @click="detailDialogRef.openDialog(scope.row, '销售退货详情')">
              {{ scope.row.code }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop='documentStatus' label='单据状态' show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.documentStatus)" size="small">
              {{ getStatusText(scope.row.documentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop='returnDate' label='退货日期' show-overflow-tooltip />
        <el-table-column prop='salesOrderNumber' label='销售单号' show-overflow-tooltip />
        <el-table-column prop='customerName' label='客户名称' show-overflow-tooltip />
        <el-table-column prop='contactPerson' label='联系人' show-overflow-tooltip />
        <el-table-column prop='contactMethod' label='联系方式' show-overflow-tooltip />
        <el-table-column prop='salesDeptId' label='销售部门' show-overflow-tooltip>
          <template #default="scope">
            {{ getOrgName(scope.row.salesDeptId) }}
          </template>
        </el-table-column>
        <el-table-column prop='salesManagerId' label='销售负责人' show-overflow-tooltip>
          <template #default="scope">
            {{ getUserName(scope.row.salesManagerId) }}
          </template>
        </el-table-column>
        <el-table-column prop='salesReturnQuantity' label='销售退货数量' show-overflow-tooltip>
          <template #default="scope">
            {{ getSalesReturnQuantity(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop='returnReason' label='退货原因' show-overflow-tooltip />
        <el-table-column prop='remark' label='备注' show-overflow-tooltip />
        <el-table-column prop='deleteTime' label='软删除时间' show-overflow-tooltip />
        <el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <ModifyRecord :data="scope.row" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right" show-overflow-tooltip v-if="auth('syssalesreturnorder:update') || auth('syssalesreturnorder:delete')">
          <template #default="scope">
            <el-button icon="ele-Edit" size="small" text type="primary" @click="editDialogRef.openDialog(scope.row, '编辑销售退货')" v-auth="'syssalesreturnorder:update'"> 编辑 </el-button>
            <el-button icon="ele-Check" size="small" text type="success" @click="initiateAudit(scope.row)" v-if="scope.row.documentStatus === 1"> 发起审核 </el-button>
            <el-button icon="ele-Delete" size="small" text type="primary" @click="delSyssalesreturnorder(scope.row)" v-auth="'syssalesreturnorder:delete'"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination 
              v-model:currentPage="state.tableParams.page"
              v-model:page-size="state.tableParams.pageSize"
              @size-change="(val: any) => handleQuery({ pageSize: val })"
              @current-change="(val: any) => handleQuery({ page: val })"
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 50, 100, 200, 500]"
              :total="state.tableParams.total"
              size="small"
              background />
      <ImportData ref="importDataRef" :import="syssalesreturnorderApi.importData" :download="syssalesreturnorderApi.downloadTemplate" v-auth="'syssalesreturnorder:import'" @refresh="handleQuery"/>
      <printDialog ref="printDialogRef" :title="'打印销售退货'" @reloadTable="handleQuery" />
      <editDialog ref="editDialogRef" @reloadTable="handleQuery" />
      <detailDialog ref="detailDialogRef" @reloadTable="handleQuery" @edit="(row) => editDialogRef.openDialog(row, '编辑销售退货')" />
    </el-card>
  </div>
</template>
<style scoped>
:deep(.el-input), :deep(.el-select), :deep(.el-input-number) {
  width: 100%;
}
</style>